/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: UnprocessedMessageObserver.java
 * Author: ckj
 * Date: 2024/7/21 下午10:15
 * Description:
 * <p>
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.server;

import com.bosssoft.message.ServerMessage;
import com.bosssoft.utils.WriterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;


/**
 * @author ckj
 */
public class UnprocessedMessageObserver implements UserObserver {
    private static final Logger logger = LoggerFactory.getLogger(UnprocessedMessageObserver.class);

    /**
     *
     * @author ckj
     * @date 2024/07/22 下午4:35
     * 更新用户消息
     */
    @Override
    public void updateNewUser(String userName, Socket socket) throws IOException {
        logger.info("{}用户已上线",userName);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
        if (ChatServerWithClientIdentification.getMessageMap().containsKey(userName)){
            ArrayList<String> strings = new ArrayList<>();
            strings.add("你有未处理的消息");
            ServerMessage serverMessage = new ServerMessage().build(strings);
            try {
                WriterUtil.writeToUser(writer,serverMessage.convertFromTransferableDataList());
                ChatServerWithClientIdentification.getMessageMap().get(userName).forEach(message -> {
                    try {
                        WriterUtil.writeToUser(writer,message.convertFromTransferableDataList());
                    } catch (Exception e) {
                        logger.error("输出失败");
                    }
                });
            } catch (Exception e) {
                logger.error("输出失败");
            }
        } else {
            ArrayList<String> strings = new ArrayList<>();
            strings.add("你没有有未处理的消息");
            ServerMessage serverMessage = new ServerMessage().build(strings);
            try {
                WriterUtil.writeToUser(writer,serverMessage.convertFromTransferableDataList());
            } catch (Exception e) {
                logger.error("输出失败");
            }
        }
    }

}